<?php

namespace App\Http\Controllers\UserCenter;

use App\Http\Controllers\Component\MasterResponseController;
use App\Model\Address;
use App\Model\ChinaCity;
use App\Model\ChinaCounty;
use App\Model\ChinaProvince;
use App\Model\ChinaRegion;
use Auth;
use App\Http\Requests\UserCenter\MyAddressRequest;

class MyAddressController extends MasterResponseController
{

    public function __construct()
    {
        $this->middleware('unlogin');
    }

    public function index()
    {
        $provinces = ChinaProvince::all();
        $myAddresses = Address::where('user_id', Auth::user()->id)->get();
        $data = array(
            'provinces' => $provinces,
            'myAddresses' => $myAddresses
        );
        return view('user_center.myAddress', compact('data'));
    }

    public function getCity($id)
    {
        $cities = ChinaCity::where('province_id', $id)->get();
        return parent::withData($cities);
    }

    public function getCounty($id)
    {
        $counties = ChinaCounty::where('city_id', $id)->get();
        return parent::withData($counties);
    }

    public function getRegion($id)
    {
        $regins = ChinaRegion::where('county_id', $id)->get();
        return parent::withData($regins);
    }


    public function addAddress(MyAddressRequest $request)
    {
        $count = Address::where('user_id', $request['user_id'])->count('*');
        if ($count < 5) {
           $newAddress= Address::create($request->all());
            return $this->successWithData('新地址已添加',$newAddress);
        } else {
            return parent::error('抱歉，最多只能设置5个地址');
        }

    }

    public function changeAddress(MyAddressRequest $request)
    {
        $address=Address::where('id',$request['id'])->first();
        $address->name=$request['name'];
        $address->phone=$request['phone'];
        $address->province_id=$request['province_id'];
        $address->province=$request['province'];
        $address->city_id=$request['city_id'];
        $address->city_id=$request['city_id'];
        $address->county_id=$request['county_id'];
        $address->county=$request['county'];
        $address->region_id=$request['region_id'];
        $address->region=$request['region'];
        $address->detail_address=$request['detail_address'];
        $address->save();
        return parent::successWithData('地址信息已修改！',$address);
    }

    public function deleteAddress($id)
    {
        Address::where('id',$id)->delete();
        return parent::success('删除成功');
    }
}
